package com.zt.weibo.main;


import android.app.ProgressDialog;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.zt.weibo.R;
import com.zt.weibo.WeiboApp;
import com.zt.weibo.interfaces.IWeiboPopListener;
import com.zt.weibo.interfaces.IWeiboServiceListener;
import com.zt.weibo.utils.PrintLog;
import com.zt.weibo.vo.CommentInfo;
import com.zt.weibo.vo.EnumSendType;
import com.zt.weibo.vo.StatusInfo;
import com.zt.weibo.vo.WeiboInfo;

/**
 * 用于发送微博的弹窗，默认发布的类型是普通微博。
 * 如有需要，使用setSendType方法设置发布类型和微博数据类。
 * @author zhaotong
 */
public class WeiboSendPopwin
{
	private PopupWindow	mPopWin	= null;
	private View	mContentView = null;
	private View	mParentView = null;
	private IWeiboPopListener mListener = null;
	private Context mContext = null;
	private EditText mEditText = null;
	private TextView mNumText = null;
	private Button	mConfirmBtn = null;
	private Button	mCancelBtn = null;
	private SendListener sendListener = null;
	private boolean bIsSend = false;
	private EnumSendType eSendType = EnumSendType.E_SEND_STATUS;
	private StatusInfo mStatusInfo = null;
	private CommentInfo mCommentInfo = null;
	private ProgressDialog mWaitDialog = null;
	
	/**
	 * 用于发送微博的弹窗，默认发布的类型是普通微博。
	 * 如有需要，使用setSendType方法设置发布类型和微博数据类。
	 * @param con Context
	 * @param parentView 父View
	 * @param listener 回调接口
	 */
	public WeiboSendPopwin(Context con, View parentView, IWeiboPopListener listener)
	{
		mContext = con;
		mParentView = parentView;
		mListener = listener;
		mContentView = LayoutInflater.from(mContext).inflate(R.layout.weibo_send_popwin, null);
		mPopWin = new PopupWindow(mContentView, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		mPopWin.setFocusable(true);
		mPopWin.setOutsideTouchable(false);
		mPopWin.setAnimationStyle(R.style.popwin_animation);
		mWaitDialog = new ProgressDialog(mContext);
		mWaitDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mWaitDialog.setMessage(mContext.getString(R.string.progress_dialog_sending));
		mEditText = (EditText) mContentView.findViewById(R.id.weibo_send_edittext);
		mNumText = (TextView) mContentView.findViewById(R.id.weibo_send_numtext);
		mConfirmBtn = (Button) mContentView.findViewById(R.id.weibo_send_confirm);
		mCancelBtn = (Button) mContentView.findViewById(R.id.weibo_send_cancel);
		sendListener = new SendListener();
		setListener();
	}
	
	private void setListener()
	{
		ClickListener clickListener = new ClickListener();
		TouchListener touchListener = new TouchListener();
		KeyListener keyListener = new KeyListener();
		TextListener textListener = new TextListener();
		mConfirmBtn.setOnClickListener(clickListener);
		mCancelBtn.setOnClickListener(clickListener);
		mConfirmBtn.setOnTouchListener(touchListener);
		mCancelBtn.setOnTouchListener(touchListener);
		mEditText.setOnKeyListener(keyListener);
		mEditText.addTextChangedListener(textListener);
	}
	
	/**
	 * 如需发布非普通微博，在此设置类型和微博数据类。
	 * @param eSendType 微博发布类型枚举类，包括：普通、转发、转发原微博、评论、回复评论
	 * @param weiboInfo 微博数据类，发布类型为普通可以为NULL。
	 */
	public void setSendType(EnumSendType eSendType, WeiboInfo weiboInfo)
	{
		this.eSendType = eSendType;
		switch(eSendType)
		{
		case E_SEND_STATUS:
		case E_SEND_REPOST:
		case E_SEND_REPOST_ORI:
		case E_SEND_COMMENT:
			this.mStatusInfo = (StatusInfo)weiboInfo;
			break;
		case E_SEND_REPLAY:
			this.mCommentInfo = (CommentInfo)weiboInfo;
		}
	}
	
	/**
	 * 显示弹窗。根据发布类型做一些改变
	 */
	public void show()
	{
		try
		{
			mPopWin.showAtLocation(mParentView, Gravity.CENTER, 0, 0);
			switch(eSendType)
			{
			case E_SEND_STATUS:
			case E_SEND_COMMENT:
			case E_SEND_REPLAY:
			case E_SEND_REPOST_ORI:
				mEditText.setText("");
				break;
			case E_SEND_REPOST:
				if(mStatusInfo.bIsRetweetOther)
				{
					mEditText.setText(" //@" + mStatusInfo.mUserInfo.strName + "：" + mStatusInfo.strContent);
				}
				else
				{
					mEditText.setText("");
				}
				break;
			}
			mEditText.requestFocus();
			mEditText.setSelection(0);
			bIsSend = false;
			if(null != mListener)
			{
				mListener.onPopShow();
			}
			WeiboApp.mHandler.postDelayed(new Runnable() {
				
				@Override
				public void run()
				{
					InputMethodManager imm = (InputMethodManager) mContext.
							getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.showSoftInput(mEditText, InputMethodManager.SHOW_IMPLICIT);
				}
			}, 50);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 消隐弹窗，如果发布了微博就回调相应的接口，如果没发布就不干事。
	 * 不论如何将发布类型置为普通微博。
	 */
	public void dismiss()
	{
		try
		{
			if(null != mPopWin && mPopWin.isShowing())
			{
				mPopWin.dismiss();
				if(bIsSend)
				{
					if(null != mListener)
					{
						mListener.onPopDismiss();
					}
				}
				eSendType = EnumSendType.E_SEND_STATUS;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 发布微博，根据eSendType来做一些改变。
	 */
	private void sentWeibo()
	{
		String str = mEditText.getText().toString();
		if(null == str || "".equals(str))
		{
			Toast.makeText(mContext, mContext.getString(R.string.toast_no_words), 1000).show();
		}
		else
		{
			switch(eSendType)
			{
			case E_SEND_STATUS:
				WeiboApp.mServer.sentStatus(str, sendListener);
				break;
			case E_SEND_REPOST:
				WeiboApp.mServer.repostStatus(mStatusInfo.strId, str, 0, sendListener);
				PrintLog.debug("发布界面：要转发的微博ID = " + mStatusInfo.strId + "\n" 
						+ "要转发的内容 = " + mStatusInfo.strContent);
				break;
			case E_SEND_REPOST_ORI:
				String strId = "";
				if(mStatusInfo.bIsRetweetOther)
				{
					strId = mStatusInfo.mRetweetInfo.strId;
				}
				else
				{
					strId = mStatusInfo.strId;
				}
				WeiboApp.mServer.repostStatus(strId, str, 0, sendListener);
				break;
			case E_SEND_COMMENT:
				WeiboApp.mServer.commentStatus(mStatusInfo.strId, str, 0, sendListener);
				PrintLog.debug("发布界面：要评论的微博ID = " + mStatusInfo.strId + "\n" 
						+ "评论的内容 = " + str);
				break;
			case E_SEND_REPLAY:
				WeiboApp.mServer.replyComment(mCommentInfo.strId, mCommentInfo.mStatusBeenCommented.strId, 
						str, 0, sendListener);
				break;
			}
		}
	}
	
	private class ClickListener implements OnClickListener
	{
		@Override
		public void onClick(View v)
		{
			switch(v.getId())
			{
			case R.id.weibo_send_confirm:
				sentWeibo();
				break;
			case R.id.weibo_send_cancel:
				bIsSend = false;
				dismiss();
				break;
			}
		}
	}
	
	private class TouchListener implements OnTouchListener
	{
		@Override
		public boolean onTouch(View v, MotionEvent event)
		{
			v.requestFocus();
			return false;
		}
		
	}
	
	private class KeyListener implements OnKeyListener
	{
		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event)
		{
			if(keyCode == KeyEvent.KEYCODE_BACK)
			{
				dismiss();
				return true;
			}
			return false;
		}
	}
	
	private class TextListener implements TextWatcher
	{
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after)
		{
			
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{
			
		}

		@Override
		public void afterTextChanged(Editable s)
		{
			mNumText.setText(140 - s.toString().length() + "");
		}
	}
	
	/**
	 * 调用微博API的回调接口类
	 * @author zhaotong
	 */
	private class SendListener implements IWeiboServiceListener
	{
		@Override
		public void onStart()
		{
			mWaitDialog.show();
		}

		@Override
		public void onCompl(String strJson)
		{
			mWaitDialog.dismiss();
			Toast.makeText(mContext, mContext.getString(R.string.toast_send_success), 
					1000).show();
			bIsSend = true;
			dismiss();
		}

		@Override
		public void onError(String str)
		{
			Toast.makeText(mContext, mContext.getString(R.string.toast_send_error), 
					1000).show();
			bIsSend = false;
			dismiss();
		}
	}
}
